import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Modal,Tools,Button,List,WhiteSpace,Bubble,Icon,ActionSheet,ActivityIndicator,PhotoSwipe,Toast } from 'weaver-mobile';
import {Route, withRouter } from 'react-router-dom';
import { RouteLayout,Form,Upload } from 'weaver-mobile-page';
import AlertPage from '../../public/alertPage/AlertPage';
import AddInvoice from '../remember/AddInvoice'
import {openWorkFlow,_scanQRCode,_chooseInvoice,getCpUser} from '../../util/pulic-func'
import DetailPage from '../wallet/DetailPage'
import ToWallet from '../wallet/ToWallet'
import AutoCheck from '../reception/AutoCheck'
import ToOcr from '../remember/ToOcr';
import ToEnterByHand from '../remember/ToEnterByHand';
require('../../public/icon/iconfont');
const getLabel = Tools.getLabel;
const WeaAlert = Modal.alert;


const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}
  
const now = new Date();

@withRouter
@inject ('rememberStore','baseStore')
@observer
class ToRememberDetailPage extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            sValue: [],
            list: [], 
            showCalendar: false, 
            dataShow:false, //控制 无数据内容是否显示     
            _key:0
        }

        this.sreenHeight = 0;  

    }

    static defaultProps = {
        prefixCls:"fna-advancedForm"
    }

    componentWillMount(){
        const {baseStore} = this.props;
        const { getTheme,getEquipmentFn } = baseStore;
        getTheme();
        getEquipmentFn();
    }    

    componentDidMount() {
        const { rememberStore,location:{search,pathname},toRememberDetailPageData,baseStore } = this.props;
        const { getTakeOneNoteSetPage,getTakeOneNoteSetInvoicePage,getTakeOneNoteSetselect,setInfo,getInvoiceCreatWorkflow } = rememberStore;  
        const { invoiceCloudInfo,getInvoiceCloudToken } = baseStore; 

        this.sreenHeight = document.documentElement.clientHeight;

        let _urlParam = JSON.parse(sessionStorage.getItem('rememberDetailPageInfo')) == null ? {} : JSON.parse(sessionStorage.getItem('rememberDetailPageInfo'));
        let params = {
            id:toRememberDetailPageData.id || _urlParam.id,
            valueId:toRememberDetailPageData.valueId || _urlParam.valueId,
            option:toRememberDetailPageData.isReimbursed || _urlParam.isReimbursed,
            currentRoute:pathname || _urlParam.currentRoute
        };
        
        setInfo(toRememberDetailPageData);
        //存数据到 sessionStorage
        sessionStorage.setItem('rememberDetailPageInfo',JSON.stringify(toRememberDetailPageData));

        getTakeOneNoteSetPage(params,(value)=>{
            this.setState({
                list:value.valueList
            })
        });
        getTakeOneNoteSetInvoicePage({...params});

        if(invoiceCloudInfo.invoiceCloud == undefined){
            getInvoiceCloudToken({},()=>{
                const { invoiceCloudInfo } = this.props.baseStore;
                {invoiceCloudInfo.invoiceCloud === false && getTakeOneNoteSetselect(params)};
            });
        }else{
            {invoiceCloudInfo.invoiceCloud === false && getTakeOneNoteSetselect(params)};
        }

        getInvoiceCreatWorkflow({ids:params.id});
        
        window.addEventListener('message',this.receiver,false);
        
    }

    componentWillUnmount(){
        const { rememberStore,refresh } = this.props;
        const { clearData } = rememberStore;   
        clearData(); 
        refresh();
        ActionSheet.close();
        sessionStorage.removeItem('rememberDetailPageInfo');
        window.removeEventListener('message',this.receiver,false);
    }


    render() {
        const { rememberStore,prefixCls,baseStore } = this.props;
        const { form,imageId,icon,title,info,invoiceIds,invoiceList,loading_type,tjfpfieldType,invoiceResult,checkJson } = rememberStore;
        const { detailPageRoute_AB,adRoute_AB,toAutoCheckRoute_AB,toOcrRoute_AB,toEnterByHand_AB,enabled,tjfpInvoiceId,setInvoiceIds,setInvoiceList } = rememberStore;
        const { invoiceCloudInfo,theme,getInvoiceCloudUrl } = baseStore;

        let _enabled,disabledInvoice = '';
        if(invoiceCloudInfo.invoiceCloud === true){
            _enabled = JSON.stringify(enabled);
            disabledInvoice = invoiceIds ? invoiceIds.match(/./g) : [];  
        }
        
        return (
            
                <div className={`${prefixCls}`}>
                    <ActivityIndicator
                        toast
                        text="Loading..."
                        animating={loading_type}
                    />
                    {
                        <div className={'invoiceModal'}>
                            <header>
                                <div>
                                    {imageId == '0' ? <div className={`fna-flex-icon-item-icon ${icon}_div`}><Icon type={icon}/></div> : <div><img src={`/weaver/weaver.file.FileDownload?fileid=${imageId}&cwid=fnaRemember`} width="22" height="18" style={{marginTop:'6px'}}/></div>}
                                    <span>{title}</span>
                                </div>
                                <img src={'/images/fna/fnaMobile/line.png'} width="100%"/>
                            </header>
                            
                            <Form store={form} onChange={this.onChange} style={{height:(this.sreenHeight-140)}}>
                                
                                <List>
                                    {this.getFields()}
                                </List>

                                <WhiteSpace />
                                
                            </Form>
                            {false && <AlertPage show={true} icon="no-data" msg={getLabel(83553, "暂无数据")} ></AlertPage>}
                        </div>
                    }
                    
                    {/* 根据  valueId  判断是否是 编辑 和查看状态*/}
                    {info.valueId ? 
                        <footer className={'fna-advanceForm-footer fna-advanceForm-footer-edit'} >
                            <div className={info.isReimbursed == '1' ? 'fna-unselected-div' : ''} onClick={()=>this.delete()}><Icon type="delete" size={'xs'}/><div>{getLabel(91,'删除')}</div></div>
                            <div className={info.isReimbursed == '1' ? 'fna-unselected-div' : ''} onClick={()=>this.handleSubmit('reimbursement')}><Icon type="initiate-reimbursement" size={'xs'}/><div>{getLabel(383848,'发起报销')}</div></div>
                            <Button type="primary" disabled={info.isReimbursed == '1' ? true : false} onClick={()=>{this.handleSubmit('save')}}  style={{ marginRight: '4px' }}>{getLabel(86,'保存')}</Button>
                        </footer>
                        :
                        <footer className={'fna-advanceForm-footer fna-advanceForm-footer-view'} >
                            <Button type="gost" onClick={()=>{this.handleSubmit('another');}}  style={{ marginRight: '4px' }}>{getLabel(517374,'再记一笔')}</Button>
                            <Button type="primary" onClick={()=>{this.handleSubmit('save')}}  style={{ marginRight: '4px' }}>{getLabel(86,'保存')}</Button>
                        </footer>
                    }

                    {/* 跳转到 我的票夹  --  发票详情 */}
                    <Route
                        key={detailPageRoute_AB.id}
                        path={detailPageRoute_AB.path}
                        render={() => (
                            <RouteLayout>
                                <div
                                    key="wmPoutePageDemo"
                                    className="wm-route-layout wm-demo-route-layout-page"
                                >
                                    <DetailPage 
                                        reset_tjfj={()=>{
                                            let invoiceIdsArr = invoiceIds.split(',');
                                            let index = invoiceIdsArr.indexOf(tjfpInvoiceId);
                                            invoiceIdsArr.splice(index,1);
                                            let params = invoiceIdsArr.join(',');
                                            if(!params){
                                                setInvoiceIds();
                                                setInvoiceList();
                                            }
                                            this.reset_tjfj(params)
                                        }}
                                    />
                                </div>
                            </RouteLayout>
                        )}
                    />
                    
                    <Route
                        key={adRoute_AB.id}
                        path={adRoute_AB.path}
                        render={() => (
                            <RouteLayout>
                                <div
                                    key="wmPoutePageDemo"
                                    className="wm-route-layout wm-demo-route-layout-page"
                                >
                                    <ToWallet 
                                        info={info}
                                        invoiceIds={invoiceIds}
                                        checkStatusquey={1}
                                        reset_tjfj={(value)=>{
                                            this.reset_tjfj(value)
                                        }}
                                        tjfpfieldType={tjfpfieldType}
                                    />
                                </div>
                            </RouteLayout>
                        )}
                    />

                    <Route
                        key={toAutoCheckRoute_AB.id}
                        path={toAutoCheckRoute_AB.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        <AutoCheck 
                                            isForm={true} 
                                            invoiceResult={invoiceResult} 
                                            checkJson={checkJson} 
                                            reset_tjfj={(value)=>{this.reset_tjfj(value)}}
                                            invoiceIds={invoiceIds}  
                                        />
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 

                    <Route
                        key={toOcrRoute_AB.id}
                        path={toOcrRoute_AB.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        <ToOcr 
                                            invoiceIds={invoiceIds}  
                                            reset_tjfj={(value)=>{
                                                this.reset_tjfj(value)
                                            }}
                                        />
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 

                    <Route
                        key={toEnterByHand_AB.id}
                        path={toEnterByHand_AB.path}
                        render={() => {
                            return (
                                <RouteLayout getContainer={() => document.getElementById("root")}>
                                    <div
                                        key="crmListLayout"
                                        className="wm-route-layout"
                                    >
                                        <ToEnterByHand 
                                            invoiceIds={invoiceIds}  
                                            reset_tjfj={(value)=>{
                                                this.reset_tjfj(value)
                                            }}
                                        />
                                    </div>
                                </RouteLayout>
                            )
                        }}
                    /> 

                    <Route path={`/accountBook/toRememberDetailPageRoute/viewframe`} render={() => {           
                        return <RouteLayout>
                            <div key={'viewframe'} className="wm-route-layout">
                                <iframe 
                                    className='ec-iframe' 
                                    src={getInvoiceCloudUrl('rememberDetailPage',4,{theme:encodeURIComponent(JSON.stringify(theme)),enabled:encodeURIComponent(_enabled),disabledInvoice:encodeURIComponent(JSON.stringify(disabledInvoice))})}
                                    style={{width:'100%',height:'100%',border:'0'}}
                                    id={"myIframe"} 
                                >
                                </iframe>
                            </div>
                        </RouteLayout>
                    }}/> 

                    <RouteLayout.Frame
                        id="invoiceframe"
                        path={'/RememberDetailPage/invoiceframe'}
                        iframeProps={{
                            src:getInvoiceCloudUrl('rememberDetailPage',5,{id:rememberStore.cloudId})
                        }}
                        key={this.state._key}
                    />    

                </div>
            
        )
    }


    getFields = () => {
        const { rememberStore,baseStore } = this.props;
        const { form,datas,uploadStore1,invoiceList,tjfj,tjfp,uploadParams,setDatas,info,priceTaxSum,hasDataNumber } = rememberStore;
        const { invoiceCloudInfo } = baseStore;

        let _hasDataNumber = Number.isNaN(hasDataNumber) ? 0 : hasDataNumber;
        const { conditioninfo, isInit,formParams } = form;
        

        const fields = [];
        if (isInit) {
            toJS(conditioninfo[0].items).map((item,index) => {
                if(item.domkey[0] == tjfp){ //添加发票
                    let comment = '';

                    if(invoiceList.length > 0){
                        comment = <AddInvoice 
                                    invoiceList={invoiceList} 
                                    wfClick={(value)=>this.wfClick(value)} 
                                    deleteInvoice={(value,e)=>this.deleteInvoice(value,e)}
                                    currentInvoiceOcClick={(value,cloudId)=>this.currentInvoiceOcClick(value,cloudId)}
                                />;
                            
                    }else {
                        comment = 
                            <div className={'noAddAttachment'}>
                                <Icon type='invoice-1'  size={'md'}/>
                                <div>{getLabel(517376,'没有添加发票')}</div>
                                <div className={'addBtnCss'}  onClick={()=>{info.isReimbursed == '1' ? '' : this.showActionSheet()}}>
                                    <Icon type={'tianjia'} />
                                    <span>{getLabel(611,'添加')}</span>
                                </div>
                            </div>
                    }
                    

                    fields.push(
                        <div className={'addAttachment'} key={item.domkey.join('__')}>
                            <WhiteSpace style={{background: '#F2F7FF'}}/>
                            {invoiceList.length > 0 && <div className={'fna-tjfp-top'}>
                                <div><Icon type={'add-invoice'}/>{getLabel(517020,'添加发票')}</div>
                                <div><span>{priceTaxSum}</span></div>
                            </div>}
                            {comment}
                            {invoiceList.length > 0 &&<div className={'addBtnCss'} onClick={()=>{info.isReimbursed == '1' ? '' : this.showActionSheet()}}>
                                <Icon type={'tianjia'} />
                                <span>{getLabel(611,'添加')}</span>
                            </div>}
                            <WhiteSpace style={{background: '#F2F7FF'}}/>
                        </div>
                        
                    )
                }else if(item.domkey[0] == tjfj){

                    let comment = '';

                    if(datas.length > 0){
                        comment = 
                            <div className={'tjfj-haveContent'}>
                               {datas.map(items =>{
                                   return (
                                       <div key={items.fileid} className={'tjfj-haveContent-wrap'}>
                                           <div className={'tjfj-field'}>
                                                {(items.fileExtendName == 'jpg' || items.fileExtendName == 'png' || items.fileExtendName == 'jpeg') && <Icon type="pic" color={'#009EFB'}/>}
                                                {items.fileExtendName == 'pdf' && <Icon type="excel" color={'#64D16F'}/>}

                                                {/* <img src={items.imgSrc} /> */}
                                           </div>
                                           <div className={'tjfj-btns'}>
                                                {items.fileExtendName == 'pdf' && <a href={`/weaver/weaver.file.FileDownload?fileid=${items.fileid}&cwid=fna`}>{items.filename}</a>}
                                                {items.fileExtendName != 'pdf' && <a onClick={()=>this.imgOnClick(items.loadlink)}>{items.filename}</a>}
                                               <div>
                                                    <Button type='gost' disabled={info.isReimbursed == '1' ? true : false} onClick={()=>{this.deleteFile(items.fileid)}}>{getLabel(91,'删除')}</Button>
                                                    <Button type="gost" disabled={info.isReimbursed == '1' ? true : false} onClick={()=>{this.downFile(items.loadlink)}}>{getLabel(258,'下载')}</Button>
                                                    {invoiceCloudInfo.invoiceCloud === false && <Button type="gost" disabled={info.isReimbursed == '1' ? true : false} onClick={()=>{this.toInvoice(items.fileid)}}>{getLabel(517817,'附件转发票')}</Button>}
                                               </div>
                                           </div>
                                       </div>
                                   )
                               })}
                            </div>
                    }else{
                        comment = 
                            <div className={'tjfj-noContent'}>
                                <Icon type='no-attachment'  size={'md'}/>
                                <div>{getLabel(517377,'没有添加任何附件')}</div> 
                            </div>
                    }
                    // console.log('uploadParams',uploadParams)

                    fields.push(
                        <div className={'tjfj'} key={item.domkey.join('__')}>
                            <WhiteSpace style={{background: '#F2F7FF'}}/>
                            {datas.length > 0 && <div className={'tjfj-title'}>{getLabel(517378,'增值税发票')}</div>}
                            {comment}
                            {info.isReimbursed == '1' ? 
                                <div className={'addBtnCss'} style={{textAlign:'center'}}>
                                    <Icon type={'tianjia'} />
                                    <span>{getLabel(611,'添加')}</span>
                                </div>
                                :
                                <Upload
                                    store={uploadStore1}
                                    datas={datas}
                                    uploadUrl={uploadParams.uploadUrl}
                                    editable={false}
                                    onChange={this.uploadOnChange}
                                    maxUploadSize={uploadParams.maxUploadSize}
                                    maxFilesNumber={uploadParams.maxFilesNumber}
                                    multiSelection={uploadParams.multiSelection}
                                    showUploader={true}
                                    showUploadTime={true}
                                    useJemUpload={true}
                                    showLoad={false}
                                    limitType={"jpg,jpeg,png,pdf"}
                                    onUploading={(status)=>{
                                        if(status === "uploaded"){
                                            setDatas(this.state.list) 
                                        }
                                    }}
                                >
                                    <div className={'addBtnCss'}>
                                        <Icon type={'tianjia'} />
                                        <span>{getLabel(611,'添加')}</span>
                                    </div>
                                </Upload>
                            }
                            <WhiteSpace style={{background: '#F2F7FF'}}/>
                        </div>

                    )
                } else{
                    if(info.valueId){//编辑
                        (!this.state.dataShow && !formParams[item.domkey[0]] && item.viewAttr != 3) ?
                            '' :
                            fields.push(<Form.Item
                                key={item.domkey.join('__')}
                                form={form}
                                fieldConfig={item}
                                onChange={form.onChange}
                            />)
                        
                    }else{//新建
                        fields.push(<Form.Item
                            key={item.domkey.join('__')}
                            form={form}
                            fieldConfig={item}
                            onChange={form.onChange}
                            
                        />)
                    }  

                    //添加 是否展示/收起  按钮
                    if(info.valueId && index == _hasDataNumber){
                        let dataShowBtn = <div 
                            onClick={()=>{this.setState( (preState) =>({
                                dataShow:!preState.dataShow
                            }))}} 
                            className={`fna-advanceForm-dataShowBtn`}>
                                {this.state.dataShow ? getLabel(520286,'收起未填写内容') : getLabel(520076,'显示未填写内容') }
                                {this.state.dataShow ? <Icon type='icon-xiangshang' size={'xs'}/> : <Icon type='icon-xiangxia' size={'xs'}/> }
                            </div>
                        fields.push(dataShowBtn)
                    }
                    
                }
                   
            })
            return fields;
        }
        
    }    

    //保存
    handleSubmit = (type) =>{
        const {rememberStore} = this.props;
        const { form,saveTakeOneNoteSet,getTakeOneNoteSetPage,getTakeOneNoteSetInvoicePage,getTakeOneNoteSetselect,getInvoiceCreatWorkflow,
            invoiceIds,info,tjfp,tjfj,setInfo,datas } = rememberStore;

       //判断是否存在发票
        form.updateField(tjfp, invoiceIds);

        if(datas.length > 0){//判断是否存在附件
            let temp = [];
            datas.map(items =>{
                temp.push(items.fileid);
            })
            form.updateField(tjfj, temp);
        }else{
            form.updateField(tjfj, '');
        }

        let formParams = form.formParams;

        let pass = form.doValidate().pass;
        if(pass){
            saveTakeOneNoteSet({
                ...formParams,
                valueId:info.valueId,
                id:info.id
            },(value)=>{
                Bubble.success(getLabel(22619, "保存成功"));
                let params = {
                    id:info.id,
                    valueId:value.valueId
                };
                setInfo(params);
                getTakeOneNoteSetPage(params);
                getTakeOneNoteSetInvoicePage(params);
                getTakeOneNoteSetselect(params);
                getInvoiceCreatWorkflow({ids:params.id});
                if(type == 'another'){
                    this.props.history.go(-1)
                }else if(type == 'reimbursement'){
                    this.reimbursement();
                }
            })
        }else{
            Bubble.error(form.doValidate().message);
            return false;
        }
    } 
    
    //重置 添加发票数据
    reset_tjfj = (value) =>{
        const {rememberStore} = this.props;
        const { getTakeOneNoteSetInvoicePage,info } = rememberStore;
        let params ={
            id:info.id,
            invoicesIds:value,
            type:'1'
        }

        if(!value) return;
        getTakeOneNoteSetInvoicePage(params)
    }

    showActionSheet = (type) => {
        const {rememberStore,history,baseStore} = this.props;
        const {invoiceSelect,info,adRoute_AB,getInvoiceInfoByCheck,toAutoCheckRoute_AB,toOcrRoute_AB,toEnterByHand_AB} = rememberStore;
        const {invoiceCloudInfo} = baseStore;

        if(invoiceCloudInfo.invoiceCloud === true){
            history.push('/accountBook/toRememberDetailPageRoute/viewframe')
        }else{
            let BUTTONS = invoiceSelect;
        
            ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
            },
            (buttonIndex) => {
                if(invoiceSelect[buttonIndex].id == 1){ //从票夹中选择  wallet
                    history.push(adRoute_AB.path);
                }else if(invoiceSelect[buttonIndex].id == 2){//ocr 
                    history.push(toOcrRoute_AB.path);
                }else if(invoiceSelect[buttonIndex].id == 3){//二维码
                    _scanQRCode((value)=>{
                        getInvoiceInfoByCheck({result:value},()=>{
                            history.push(toAutoCheckRoute_AB.path);
                        })
                    })
                }else if(invoiceSelect[buttonIndex].id == 4){//手动录入
                    history.push(toEnterByHand_AB.path);
                }
                
            });
        }
    }   

    //流程跳转
    wfClick = (requestId) =>{
        const {rememberStore} = this.props;
        const {invoiceIds} = rememberStore;
        openWorkFlow('view',requestId,()=>{
            this.reset_tjfj(invoiceIds)
        })
    }

    //删除发票
    deleteInvoice = (value,e) =>{
        const {rememberStore} = this.props;
        const {info,invoiceIds} = rememberStore;
        if(info.isReimbursed == '1') return;
        e.stopPropagation();
        let invoiceIdsArr = invoiceIds.split(',');
        let sub = invoiceIdsArr.indexOf(value);
        invoiceIdsArr.splice(sub,1);

        this.reset_tjfj(invoiceIdsArr);
    }

    //点击发票
    currentInvoiceOcClick = (value,cloudId) =>{
        const {rememberStore,baseStore} = this.props;
        const {info,detailPageRoute_AB,set_tjfpInvoiceId,set_cloudId} = rememberStore;
        const {invoiceCloudInfo} = baseStore;
        if(info.isReimbursed == '1') return;
        if(invoiceCloudInfo.invoiceCloud === true){
            set_cloudId(cloudId);
            this.setState((preState) =>({
                _key: preState._key == 1 ? 0 : 1
            }),function(){
                this.props.history.push('/RememberDetailPage/invoiceframe')
            })
        }else{
            this.props.history.push(detailPageRoute_AB.path+'?invoiceId='+value+'&isViewRight=true')
        }
        set_tjfpInvoiceId(value);
        
    }


    uploadOnChange = (ids, datas) => {
        const {rememberStore} = this.props;
        const {} = rememberStore;
        let uploadids = this.state.list;
        uploadids.push(datas[datas.length-1]);
        this.setState({
            list:uploadids
        })
   
    }

    //删除附件
    deleteFile = (fileid)=>{
        const {rememberStore} = this.props;
        const {datas,setDatas} = rememberStore;

        let _datas = datas;
        for(let i=0;i<_datas.length;i++){
            if(_datas[i].fileid == fileid){
                _datas.splice(i,1);
            }
        }
        this.setState({list:_datas})
        setDatas(_datas)
        
    }

    //图片预览
    imgOnClick = (url)=>{ PhotoSwipe.showImage([{url: url}], 0); }

    //下载
    downFile = (url) =>{Tools.getWeaverFile(url);}

    //附件转发票
    toInvoice = (fileid) =>{
        const {rememberStore} = this.props;
        const {doCheckInvoicePage,invoiceIds} = rememberStore;

        doCheckInvoicePage({fptpId:fileid},(value)=>{
            let ids = invoiceIds;

            if(ids == 'undefined' || ids == undefined){
                ids = value.invoiceIds;
            }else{
                ids += ','+value.invoiceIds;
            }
            this.reset_tjfj(ids)
        })
        
    }

    //底部 删除图标
    delete = () =>{
        const {rememberStore,history} = this.props;
        const {info,doDeleteRemind} = rememberStore;
        if(info.isReimbursed == '1') return;
        
        WeaAlert(getLabel(517381,'确定要删除该记一笔吗？'), '', [
            { text: getLabel(516571,'取消'), onPress: () => {}, style: 'default' },
            { text: getLabel(826,'确定'), onPress: () => {
                doDeleteRemind({
                    id:info.valueId,
                    // tableName:info.id,
                    typeId:info.id,
                },()=>{ history.go(-1) })} 
            },
        ]);
        
    }

    reimbursement = () =>{
        const {rememberStore} = this.props;
        const { workflowSelect,creatWorkflow,info,invoiceIds } = rememberStore;
        if(info.isReimbursed == '1') return
        let allMonth = workflowSelect;
        ActionSheet.showActionSheetWithOptions({
            options: allMonth,
            cancelButtonIndex: allMonth.length - 1,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        },  
        (buttonIndex) => {
            if(buttonIndex != allMonth.length - 1 && buttonIndex != 'undefined'){
                let params = {
                    workflowId:workflowSelect[buttonIndex].id,
                    id:info.id+'_'+ info.valueId
                }
                creatWorkflow(params,(value)=>{
                    openWorkFlow('view',value.requestId,()=>{
                        this.reset_tjfj(invoiceIds)
                    });
                })
                
            }
                
        });    
    }

    /* ***********************发票云********************************/
    receiver = (event) =>{
        const {equipment,invoiceCloudInfo} = this.props.baseStore;
        if (invoiceCloudInfo.jsUrl != event.origin) return;
        let returnData = event.data;
        const {match:{isExact,path},rememberStore} = this.props;
        const { invoiceIds,tjfpInvoiceId,setInvoiceList,setInvoiceIds } = rememberStore;
        console.log('toRemberDetailPage ----returnData',returnData);

        switch(returnData.type){
            case 'INVOICE':
                let arr = [];
                returnData.invoices.map( items =>{
                    arr.push(items.oaid);
                })
                arr = [...arr,...invoiceIds];
                let str = arr.join(',');
                
                this.reset_tjfj(str);

                if(!isExact && path == '/rememberDetailPage'){
                    this.props.history.goBack();
                }
                break;
            case 'ERROR':
                if(returnData.ret == '-2'){ this.sendResult('UPDATE_TOKEN'); }
                break;
            case 'ON_SCAN_QRCODE' : //调用扫码
                _scanQRCode((value) =>{
                    let params = {
                        source: "ENTRY",
                        type: "SCAN_QRCODE",
                        rid: returnData.rid , // 发票云传过来的 id
                        result: value, // 扫码结果
                    }

                    this.sendResult('SCAN_QRCODE',params);
                    
                });
                break; 
            case 'ON_SELECT_INVOICE': //选择发票   类型：1 微信  2 支付宝
                _chooseInvoice(returnData.invoiceType,(value)=>{
                    let params = {
                        source: "ENTRY",
                        type: "SELECT_INVOICE",
                        invoiceType: returnData.invoiceType, // 类型：1 微信  2 支付宝
                        rid: returnData.rid, // 发票云传过来的 id
                        list: value,
                    }
                    if(equipment.isWx === false){
                        getCpUser((value)=>{
                            params = Object.assign(params,{ appKey: value });
                            this.sendResult('SELECT_INVOICE',params);
                        })
                        
                    }else{
                        this.sendResult('SELECT_INVOICE',params);
                    }
                    
                });
                break;  
            case 'ON_CHOOSE_IMAGE': this.takePicture(this,{rid:returnData.rid}); break; 
            case 'ON_DELETE':
                let invoiceIdsArr = invoiceIds.split(',');
                let index = invoiceIdsArr.indexOf(tjfpInvoiceId);
                invoiceIdsArr.splice(index,1);
                let params = invoiceIdsArr.join(',');
                if(!params){
                    setInvoiceIds();
                    setInvoiceList();
                }
                this.reset_tjfj(params)
                break;                                 
            default :
                break;

        }
  
    } 
    
    //发送数据到 iframe
    sendResult = (type,data)=>{
        const {baseStore} = this.props;
        const {getInvoiceCloudToken} = baseStore;

        let that = this;
        switch(type){
            case 'UPDATE_TOKEN' :
                getInvoiceCloudToken({tokenUnusual:1},()=>{
                    that.sendMessage({
                        type: 'UPDATE_TOKEN',
                        token:baseStore.invoiceCloudInfo.token
                    });
                })
                break;
            case 'SCAN_QRCODE' :  
                that.sendMessage(data)
                break;
            case 'SELECT_INVOICE' :  
                that.sendMessage(data)
                break;
            case 'CHOOSE_IMAGE':
                that.sendMessage(data)
                break;
        }

    }

    //统一发送数据
    sendMessage = (data) =>{
        const {invoiceCloudInfo} = this.props.baseStore;
        let childFrame = document.getElementById("myIframe");
        let url = invoiceCloudInfo.jsUrl;
        childFrame.contentWindow.postMessage(data, url); 
    }

    //获取所有 发票拍照数据
    getlocalIdData = (params,data,send) =>{
        if(send){ 
            let localParams = {
                source: "ENTRY",
                type: "CHOOSE_IMAGE",
                rid: params.rid, // 发票云传过来的 id,
                list:data
                
            }
            
            this.sendMessage(localParams);
            
        }
    }    

    //拍照
    takePicture = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};
        console.log('takePicture---isExist',isExist);
        let that = this;
        let localIdArr = [];
        let num = 0;
        window.em_ssoInit().then(() => {

            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let localIds = res.localIds; // 返回选定照片的本地ID列表
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                num++;
                                let data = res.localData;
                                let base64PicData = "data:image/jpeg;base64,"+data;
                                let bool = localIds.length == num ? true : false;

                                let listEle = {
                                    base64:base64PicData,
                                    fileName: '',
                                }
                                localIdArr.push(listEle);

                                that.getlocalIdData(params,localIdArr,bool)

                            }
                        });
                    });

                },
                fail:function(err){
                    console.log('err',err);
                }
            });
        }).catch((res) => {
            alert("连续拍照插件异常,使用原始插件");
            // alert(JSON.stringify(res));
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }         
    

}

export default ToRememberDetailPage;